package org.cttic.visualization.visualization.websocket;

import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.cttic.visualization.visualization.websocket.vo.WebsocketModal;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@Component
@Slf4j
public class Data implements InitializingBean, ApplicationContextAware {
    private static StringRedisTemplate stringRedisTemplate;

    public static Map<String, WebsocketModal> sessionMap = new ConcurrentHashMap<>();

    public static final String websocketPre = "websocketKeySet";
    //private static ObjectMapper objectMapper = new ObjectMapper();

    public static void sendMessage(JSONObject currentVeh) {
        Set<String> members = stringRedisTemplate.opsForSet().members(websocketPre);
        if (CollectionUtils.isEmpty(members)) {
            return;
        }
        try {

            //String normal = objectMapper.writeValueAsString(currentVeh);
            for (String key : members) {
                WebsocketModal web = sessionMap.get(key);
                if (null != web && web.getOnOff()) {
                    synchronized (web) {

                        String str = currentVeh.getStr("gantryId");
                        String substring = str.substring(5, 7);
                        if (web.getProvinceId().equals(substring)) {
                            log.info("给{} =>发送信息:=>{}", substring, currentVeh);
                            web.getSession().getBasicRemote().sendText(currentVeh.toString());
                        }


                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() {
        if (stringRedisTemplate.hasKey(websocketPre)) {
            stringRedisTemplate.delete(websocketPre);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        stringRedisTemplate = (StringRedisTemplate) applicationContext.getBean("stringRedisTemplate");
    }

}
